//
//  HNLineController.m
//  shezhan
//
//  Created by 朱传正 on 2016/10/17.
//  Copyright © 2016年 haoniu. All rights reserved.
//

#import "HNLineController.h"
#import "HNMainController.h"
#import "ApplyViewController.h"

@interface HNLineController ()<UIWebViewDelegate>

@end

@implementation HNLineController

-(void)viewWillAppear:(BOOL)animated{
    [self.navigationController setNavigationBarHidden:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
      [self.navigationController.navigationBar setHidden:YES];
    
    NSString * _loginName = [NSString stringWithFormat:@"%@",[AppConfig getUserInfoByKey:@"hnLoginName"]];
    _webViewUrl = [NSMutableString stringWithFormat:@"%@%@?hnLoginName=%@",url_Base,url_XianXiaMenDian,_loginName];
    _webViewUrl = [NSMutableString stringWithFormat:@"%@",[_webViewUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest * _req = [NSURLRequest requestWithURL:[NSURL URLWithString:_webViewUrl]];
     _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0,0, mainScreenSize.width, mainScreenSize.height)];
    _webView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;
    [_webView loadRequest:_req];
    _webView.scrollView.bounces = NO;
    _webView.suppressesIncrementalRendering = NO;
    _webView.delegate = self;
    [_webView setBackgroundColor:[AppConfig colorWithHexString:@"#ececec"]];
    [self.view addSubview:_webView];
    
    //添加一个返回按钮
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 20, 40, 40)];
    [leftView setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:leftView];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"xiangyou.png"] forState: UIControlStateNormal];
    backBtn.frame = CGRectMake(5, 7, 30, 30);
    [backBtn addTarget:self action:@selector(HNPublishProductJSExportBack) forControlEvents:UIControlEventTouchUpInside];
    [leftView addSubview:backBtn];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma -mark WebView
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    NSLog(@"WebView erros is %@",error);
    if ([error code] == NSURLErrorCancelled) {
        return;
    }
    // 应用场景:加载从服务器上下载的文件,例如pdf,或者word,图片等等文件
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"error" ofType:@"html"];
    NSString *htmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    [webView loadHTMLString:htmlString baseURL:[NSURL URLWithString:filePath]];
}


-(void)HNSettingJSExportOutLogin{
    NSLog(@"HNSettingJSExportOutLogin");
    __weak HNLineController *weakSelf = self;
    [self showHudInView:self.view hint:NSLocalizedString(@"setting.logoutOngoing", @"loging out...")];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        EMError *error = [[EMClient sharedClient] logout:YES];
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf hideHud];
            if (error != nil) {
                [weakSelf showHint:error.errorDescription];
                NSLog(@"error.errorDescription = %@",error.errorDescription);
            }
            else{
                [[ApplyViewController shareController] clear];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
            }
        });
    });
}


-(void)webViewDidFinishLoad:(UIWebView *)webView{
    NSLog(@"====webViewDidFinishLoad");
    
    // Disable user selection
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
    // Disable callout
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
    
    //JS交互
    JSContext *context=[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    context[@"JavaScriptInterface"] = self;
}

- (BOOL)webView: (UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    return YES;
}

#pragma -mark HNPublishProductJSExport - 设置返回
-(void)HNPublishProductJSExportBack{
    if ([self.webView canGoBack]) {
        [self.webView goBack];
        
    }else{
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            dispatch_async(dispatch_get_main_queue(),^{
                NSLog(@"回归主线程");
                [self.view resignFirstResponder];
                [self.navigationController popViewControllerAnimated:YES];
            });
        });
    }
    NSLog(@"-------goBack---------");
}

-(NSString *)HNPublishProductJSExportReturnLoginName{
    return [[EMClient sharedClient] currentUsername];
}

@end
